//
//  Ch2Controller.swift
//  learn-gl-es-swift
//
//  Created by LimitLiu on 2019/6/30.
//  Copyright © 2019 LimitLiu. All rights reserved.
//

import UIKit
import GLKit

class Ch2_2Controller: GLController {
    var vertexBufferID: GLuint = GLuint()
    var baseEffect = GLKBaseEffect()
    var vertices: [SceneVertex2_2] = [
        SceneVertex2_2(positionCoords: vec(-0.5, -0.5, 0.0)),
        SceneVertex2_2(positionCoords: vec(0.5, -0.5, 0.0)),
        SceneVertex2_2(positionCoords: vec(-0.5, 0.5, 0.0)),
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let view = self.view as? GLView {
            view.context = GLContext(api: .openGLES2)!
            GLContext.setCurrent(view.context)
            baseEffect.useConstantColor = GLboolean(GL_TRUE)
            baseEffect.constantColor = vec(0.3, 0.6, 0.3, 1.0)
            glClearColor(0.5, 0.7, 0.5, 1.0)
            glGenBuffers(1, &vertexBufferID)
            glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBufferID)
            glBufferData(GLenum(GL_ARRAY_BUFFER), vertices.sizeof(),
                         vertices, GLenum(GL_STATIC_DRAW))
        }
    }
    deinit {
        let view = self.view as! GLView
        GLContext.setCurrent(view.context)
        if vertexBufferID != 0 {
            glDeleteBuffers(1, &vertexBufferID)
            vertexBufferID = 0
        }
        GLContext.setCurrent(nil)
    }

    override func glkView(_ view: GLView, drawIn rect: CGRect) {
        baseEffect.prepareToDraw()
        glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GLenum(GL_FLOAT),
                              GLboolean(GL_FALSE),
                              GLsizei(MemoryLayout<SceneVertex2_2>.size), nil)
        glDrawArrays(GLenum(GL_TRIANGLES), 0, GLsizei(vertices.count))
    }
}

struct SceneVertex2_2 {
    let positionCoords: GLKVector3
}
